package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.async.AuthPushAsync;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppUser;
import com.byit.domain.AppUserAuthentication;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.IAppUserAuthenticationService;
import com.byit.service.IAppUserService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * APP用户认证管理
 *
 * @author tjm
 * @date 2019年1月8日
 */
@RestController
@RequestMapping("/api/sys/userAuth")
public class AppUserAuthenticationController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppUserAuthenticationService appUserAuthenticationService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private AuthPushAsync authPushAsync;


    /**
     * 查询详情
     */
    @Log(title = "用户认证", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @PostMapping("/details")
    public Object details(@RequestParam(name = "id") Long id) {
        Page<JSONObject> data = appUserAuthenticationService.selectPageData(new Page<>(1, 1), MapBuilder.newMap(1).setParam("id", id).ok());
        return MessageResult.success(data.getRecords().get(0));
    }

    /**
     * 查询列表
     */
    @Log(title = "用户认证", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @GetMapping("/list")
    public Object list(AppUserAuthentication appUserAuthentication,
                       @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                       @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppUserAuthentication> pageInfo = new Page<>(page, limit);
        Map<String, Object> map = new HashMap<>();
        if (null != appUserAuthentication.getStatus()) {
            map.put("status", appUserAuthentication.getStatus());
        }
        if (null != appUserAuthentication.getContrast()) {
            map.put("contrast", appUserAuthentication.getContrast());
        }
        if (StringUtil.isNotEmpty(appUserAuthentication.getRealName())) {
            map.put("real_name", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(appUserAuthentication.getRealName()) + "%");
        }
        if (StringUtil.isNotEmpty(appUserAuthentication.getIdCardNo())) {
            map.put("id_card_no", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(appUserAuthentication.getIdCardNo()) + "%");
        }
        Page<JSONObject> data = appUserAuthenticationService.selectPageData(pageInfo, map);
        return MessageResult.success(data);
    }

    /**
     * 审核
     */
    @Log(title = "用户认证", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    @PostMapping("/audit")
    public Object audit(HttpSession session, @RequestParam("id") Long id,
                        @RequestParam("status") Integer status, String auditOpinion) {
        Long userId = SessionHelper.getUserId(session);
        //检查身份证是否已被其他用户认证
        AppUserAuthentication selectById = appUserAuthenticationService.selectById(id);
        List<AppUserAuthentication> appUserAuthentications = appUserAuthenticationService.selectByMap(MapBuilder.newMap(3).
                setParam("is_del", 0).setParam("id_card_no", selectById.getIdCardNo()).setParam("status", 2).ok());
        if (appUserAuthentications.size() > 1) {
            return MessageResult.error("该身份证号码已被其他用户认证");
        } else if (appUserAuthentications.size() == 1) {
            if (!appUserAuthentications.get(0).getUserId().equals(selectById.getUserId())) {
                return MessageResult.error("该身份证号码已被其他用户认证");
            }
        }
        AppUserAuthentication authentication = new AppUserAuthentication();
        authentication.setUpdateTime(new Date());
        authentication.setOperationId(userId);
        authentication.setId(id);
        authentication.setStatus(status);
        if (StringUtil.isNotEmpty(auditOpinion)) {
            authentication.setAuditOpinion(auditOpinion);
        }
        if (appUserAuthenticationService.updateById(authentication)) {

            //修改app_user表认证状态
            AppUser appUser = new AppUser();
            appUser.setId(selectById.getUserId());
            appUser.setAuthState(status);
            appUserService.updateById(appUser);
            authPushAsync.sendMsg(selectById.getUserId(), status, 0);
            return MessageResult.success();
        }
        return MessageResult.error();
    }


    /**
     * 逻辑删除
     */
//    @PostMapping("/del")
//    public Object delete(HttpSession session, @RequestParam("ids") String ids) {
//        Long userId = SessionHelper.getUserId(session);
//        List<Long> idList = StringUtil.splitLong(ids, ",");
//        for (Long id : idList) {
//            AppUserAuthentication authentication = new AppUserAuthentication();
//            authentication.setUpdateTime(new Date());
//            authentication.setOperationId(userId);
//            authentication.setId(id);
//            authentication.setIsDel(1);
//            appUserAuthenticationService.updateById(authentication);
//        }
//        return MessageResult.success();
//    }


}
